package com.shenzhenai.composebasic.components

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController

/**
 * @author huangzehui
 * @date 2025/9/17 13:16 周三
 * @description
 *
 * CompositionLocal(隐式传参) 使用
 *
 * https://www.bilibili.com/video/BV1U44y1M7F5?vd_source=e07cc8cc94eb22bd76722071b03cd199&spm_id_from=333.788.videopod.sections
 */

data class User(val name: String)

/**
 * 自定义隐式传参
 */
val LocalActiveUser = compositionLocalOf<User>(defaultFactory = {
    error("user is null")
})

@Composable
fun CompositionLocalSample() {

    val navController = rememberNavController()

    val user = User("Test")

    /**
     * localActiveUser provides user : 表示 user 赋值给 localActiveUser
     *
     * 被 CompositionLocalProvider(localActiveUser provides user) 包裹的子组件，可以使用 localActiveUser
     */
    CompositionLocalProvider(LocalActiveUser provides user) {
        NavHost(navController = navController, startDestination = "Home") {
            composable("Home") {
                HomeScreen {
                    navController.navigate("Detail")
                }
            }

            composable("Detail") {
                DetailScreen()
            }
        }
    }

}

@Composable
fun HomeScreen(onTap: () -> Unit) {
    Column {
        Text(text = "HomeScreen: ${LocalActiveUser.current.name}")
        Button(onClick = onTap) {
            Text(text = "Navigate to Detail")
        }
    }
}

@Composable
fun DetailScreen() {
    Text(text = "DetailScreen: ${LocalActiveUser.current.name}")
}


@Preview
@Composable
fun CompositionLocalSamplePreview() {
    CompositionLocalSample()
}